package com.imooc.springcloud;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @describte:接口计时过滤器
 * @program:spring-cloud-demo
 * @author:zhengdp
 * @create:2021-10-06 15:54:35
 **/
@Slf4j
@Component
//Gobal
public class TimerFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        StopWatch timer = new StopWatch();
        // 用在计时器打印的log中
        timer.start(exchange.getRequest().getURI().getRawPath());

        //exchange.getAttributes().put("requestTimeBegin",System.currentTimeMillis());
        // 回调中的业务逻辑 ==> after
        return chain.filter(exchange).then(
                // 回调逻辑
            Mono.fromRunnable(()->{
               timer.stop();
               log.info(timer.prettyPrint());
            })
        );
    }

    // 值越小，在过滤器排序列表中排越前
    @Override
    public int getOrder() {
        // pre类型，越大越优先
        // post 越小越优先
        return 0;
    }
}
